package com.hz.house.service;

import com.alibaba.fastjson.JSON;
import com.hz.house.bean.entity.CustomerBean;
import com.hz.house.bean.entity.SystemMsg;
import com.hz.house.bean.vo.ConsumerCallTemplateMsg;
import com.hz.house.bean.vo.SellManCachedBasicInfoBean;
import com.hz.house.bean.vo.SellManTemplateMsg;
import com.hz.house.common.wxmini.Value;
import com.hz.house.common.wxmini.WxMaSubscribeMessage;
import com.hz.house.dao.CustomerMapper;
import com.hz.house.enums.SystemMsgEnum;
import com.hz.house.utils.SMS.SmsSendUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统消息服务
 *
 * @author 10203
 */
@Service
@Slf4j
public class SysMsgService {

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private SmsSendUtils smsSendUtils;

    @Autowired
    private RedisCacheDataService redisCacheDataService;

    @Autowired
    private WxgzhSellHouseService wxgzhSellHouseService;

    @Autowired
    private WxMaSubscribeService wxMaSubscribeService;

    /**
     * @param toCustomer  发送给谁
     * @param content     消息内容，字符串
     * @param title       消息标题
     * @param toPageParam 点击消息后页面跳转的参数拼接
     * @param type        消息类型
     */
    public void sendSysMsg(Integer toCustomer, String content, String title, String toPageParam, SystemMsgEnum type) {
        SystemMsg msg = new SystemMsg();
        if (toCustomer == null) {
            return;
        }
        msg.setCustomerId(toCustomer);
        if (StringUtils.isEmpty(content)) {
            return;
        }
        msg.setMsg(content);
        if (StringUtils.isEmpty(title)) {
            return;
        }
        msg.setTitle(title);
        msg.setParam(toPageParam);
        if (type == null) {
            return;
        }
        msg.setMsgType(type.getId());
        msg.setCreateTime(new Date());
        msg.setMsgRead(0);
        // 消息存入数据库
        this.customerMapper.sendSysMsg(msg);
    }

    /**
     * <p>
     * 发送用户咨询了置业顾问的信息到卖房好帮手公众号
     * <p>
     * 同一客户给同一个置业顾问发模板消息提醒，半小时一次
     *
     * @param sellManCustoerId 对方的编码
     */
    public void sendSellManZiXunMsg(int sellManCustoerId) {

        // 可以发送消息，则查询发送者信息和置业顾问信息，进行模板消息推送
        SellManCachedBasicInfoBean x = this.redisCacheDataService.getSellManBasicInfo(sellManCustoerId);
        boolean isSellMan = true;
        if (ObjectUtils.isEmpty(x)) {
            log.info("模板消息推送的目标用户不是置业顾问!");
            isSellMan = false;
        }
        // 查询发送者的用户信息
        CustomerBean u = customerMapper.getUserById(sellManCustoerId);
        String name = u.getName();
        if (isSellMan) {
            String openId = x.getSellHouseWxgzhOpenid();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            SellManTemplateMsg smtm = new SellManTemplateMsg();
            smtm.setBuildingName(x.getBuildingName());
            smtm.setCustomerId(sellManCustoerId);
            smtm.setFromUserName(name);
            smtm.setFromUserTel(null);
            smtm.setZiXunTime(sdf.format(new Date()));
            wxgzhSellHouseService.sendTemplateMsgZiXunTongZhi(openId, smtm);
        }
        //推送小程序订阅消息
        if (!StringUtils.isEmpty(u.getOpenid())) {
            WxMaSubscribeMessage wxMaSubscribeMessage = new WxMaSubscribeMessage();
            wxMaSubscribeMessage.setTouser(u.getOpenid());
            wxMaSubscribeMessage.setPage(wxMaSubscribeService.MESSAGE_DETAIL_PAGE + "?sellManCustoerId=" + sellManCustoerId);
            wxMaSubscribeMessage.setTemplate_id(wxMaSubscribeService.USER_ASK_REMIND);
            Map<String, Value> params = new HashMap<>(16);
            params.put("name1", new Value(name));
            params.put("time3", new Value());
            params.put("thing4", new Value("点击跳转到买房好帮手立即回复!"));
            wxMaSubscribeMessage.setData(params);
            log.info("小程序发送订阅消息:{}", JSON.toJSONString(wxMaSubscribeMessage));
            wxMaSubscribeService.sendSubscribeMsg(wxMaSubscribeMessage);
        }

        //推送短信
        if (!StringUtils.isEmpty(x.getPhone()) || !StringUtils.isEmpty(u.getCellphone())) {
            String data = "【买房好帮手】您有新消息等待回复,请进入小程序买房好帮手查看详情!";
            smsSendUtils.sendSmsMessage(StringUtils.isEmpty(x.getPhone()) ? u.getCellphone() : x.getPhone(), data);
        }

    }

    public void encodePhoneNumber(Integer currentUserId, Integer sellManCustomerId) {
        // 可以发送消息，则查询发送者信息和置业顾问信息，进行模板消息推送
        SellManCachedBasicInfoBean x = this.redisCacheDataService.getSellManBasicInfo(sellManCustomerId);
        if (x == null) {
            log.info("模板消息推送的目标用户不是置业顾问!");
            return;
        }
        String openId = x.getSellHouseWxgzhOpenid();
        if (StringUtils.isEmpty(openId)) {
            log.info("目标置业顾问还未关注公众号或未进行绑定!");
            return;
        }
        //2019-12-16  修改为不再限制置业顾问推送消息的时间。
        // 检查该用户是否给该置业顾问30分钟内发过消息，如果有则不发，使用redis
//		if (!redisCacheDataService.setNxCustomerIdSellManId(customerId, sellManCustoerId)) {
//			log.info("该用户30分钟内给该置业顾问发送过消息,禁止再次推送");
//			return;
//		}
        // 查询发送者的用户信息
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        CustomerBean u = customerMapper.getUserById(currentUserId);
        ConsumerCallTemplateMsg cctm = new ConsumerCallTemplateMsg();
        cctm.setPhoneNumber(u.getCellphone());
        cctm.setCallDate(sdf.format(new Date()));
        wxgzhSellHouseService.sendTemplateMsgCallPhone(openId, cctm);
    }
}
